<template>
  <a-modal
    title="查看产品"
    :footer="null"
    :width="1400"
    :maskClosable="false"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>

          <a-col :span="12">
            <a-form-item
              label="产品"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入产品名称" v-decorator="['materialName', {rules: [{required: true, message: '请输入产品名称！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="序号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入序号" v-decorator="['extend1', {rules: [{required: true, message: '请输入序号！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="软件版本号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input placeholder="请输入软件版本号" v-decorator="['extend2', {rules: [{required: false, max: 25, message: '请输入不大于25位长度软件版本号！'}]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>

          <a-col :span="12">
            <a-form-item
              label="数量"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback=""
            >
              <a-input-number placeholder="请输入数量" v-decorator="['number', {rules: [{required: true, message: '请输入数量！'}]}]"
                              :disabled="disabled" :min="0" style="width: 100%"/>
            </a-form-item>
          </a-col>

          <!--        自身BOM Table组件   -->
          <a-col :span="24">
            <a-form-item
              :validate-status="bomSelfValidate.validateStatus"
              :help="bomSelfValidate.errorMsg">
              <!--        复杂的BOM Table组件   -->
              <FCBomMaterialTable ref="bomMaterialTableSelf" :default-bom="bom" :isPermission="managerOrFinance()"/>
            </a-form-item>
          </a-col>

          <!--        其它BOM Table组件   -->
          <a-col :span="24">
            <a-form-item v-for="(item, index) in otherBoms">
              <FCBomMaterialTable :ref="'bomMaterialTable'+index" :key="index" @delete="(key)=>otherBoms.splice(key,1)" :default-bom="item" :isPermission="managerOrFinance()"/>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {add, detailFull} from '@/api/modular/main/emsbom/emsBomManage'
import {listFull as emsBomMaterialListFull} from '@/api/modular/main/emsbommaterial/emsBomMaterialManage'
import FcUpload from '@/components/FCUpload/FcUpload'
import FCBomMaterialTable from '@/views/main/emsbom/FCBomMaterialTable'

export default {
  components: {
    FCBomMaterialTable,
    FcUpload,
  },
  data() {
    return {
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 15}
      },
      labelColBlock: {
        xs: {span: 24},
        sm: {span: 2}
      },
      wrapperColBlock: {
        xs: {span: 24},
        sm: {span: 20}
      },
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      formModel: {},
      bomIndexVisible: false,
      disabled: false,
      //  table 组件
      materialTypeList: [
        {key: 0, name: '原料'}, {key: 1, name: '线缆'}, {key: 2, name: '包材'},
      ],
      bom: {
        bomId: '',
        bomCode: '',
        bomName: '本次BOM',
        bomType: '',
        status: '',
        image: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
        bomMaterials: [],
        otherBoms: [],
      },
      bomMaterial: {
        bomMaterialId: '',
        bomId: '',
        bomIdSource: '',
        bomMaterialSort: '',
        materialId: '',
        materialNumber: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
      },
      bomSelfValidate: {},
      otherBoms: [],
      selfBoms: []
    }
  },
  computed: {
    outputName() {
      return this.formModel.outputObject ? this.formModel.outputObject.materialName : '选择产出物'
    }
  },
  methods: {
    add(record) {
      this.visible = true
      this.disabled = false
      setTimeout(() => {
        this.form.resetFields()
        this.form.setFieldsValue(record)
      }, 200)

      detailFull({bomId: record.bomId}).then(res => {
        this.bom = res.data
        this.otherBoms = this.bom.otherBoms
      })
    },
    disabledShow(record) {
      this.add(record)
      this.disabled = true
    },
    handleSubmit() {
      this.getSelfBomMaterialValue()
      const {form: {validateFields}} = this
      // return
      this.confirmLoading = true
      validateFields((errors, values) => {
        // this.confirmLoading = false
        if (!errors) {
          values = Object.assign({bomMaterials: this.selfBoms, otherBoms: this.otherBoms}, values)
          add(values).then((res) => {
            this.confirmLoading = false
            if (res.success) {
              this.$message.success('新增成功')
              this.handleCancel()
              this.$emit('ok', values)
            } else {
              this.$message.info('新增失败：' + res.message)
            }
          }).finally((res) => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
    },

    // upload
    handleFileListStringChange(fileListString) {
      this.form.setFieldsValue({image: fileListString})
    },
    onBomSelected(selectedBomArray) {
      console.log(`selectedBomArray:${JSON.stringify(selectedBomArray)}`)
      // 新增其它BOM,生成表格控件。数据结构为 bom，其中还需要建立关联的原料数组。
      // 同时还需要处理该BOM引用了多个原料或别的BOM的情况
      // // 表格里面显示BOM中包含的原料列表
      // 不管是普通BOM，还是组合BOM。都将引用的BOM中的原料放进同一张表中
      // 构建BOM数据
      if (selectedBomArray.length == 0) {
        this.$message.error('没有选择BOM')
        return
      }
      if (selectedBomArray.length > 1) {
        this.$message.error('暂不支持多选BOM添加')
        return
      }
      if (selectedBomArray.length > 0) {
        let selectedBom = selectedBomArray[0]
        let bomId = selectedBom.bomId
        emsBomMaterialListFull({bomId}).then(res => {
          let bomMaterials = res.data
          // 构建BOM Bean
          selectedBom.bomMaterials = bomMaterials
          this.otherBoms.push(selectedBom)
        })
      }
    },
    getSelfBomMaterialValue() {
      let tableValue = this.$refs.bomMaterialTableSelf.getTableValue()
      this.selfBoms = tableValue

      if (tableValue && tableValue.length > 0) {
        this.bomSelfValidate = {
          validateStatus: 'success',
          errorMsg: null,
        }
      } else {
        this.bomSelfValidate = {
          validateStatus: 'error',
          errorMsg: '物料清单不能为空',
        }
      }

      this.getBomTableValue()
    },
    getBomTableValue() {
      // bomMaterialTable
      for (let i = 0; i < this.otherBoms.length; i++) {
        let $refTable = this.$refs['bomMaterialTable' + i][0]
        this.otherBoms[i] = $refTable.getBom()
      }
      // for (const refsKey in this.$refs) {
      //   if (refsKey.startsWith('bomMaterialTable')) {
      //     let $refTable = this.$refs[refsKey]
      //     this.otherBoms.push($refTable.getTableValue())
      //   }
      // }
    },
    handleEmsMaterialIndex1Show() {
      this.$refs.emsMaterialIndex1.show()
    },
    onEmsMaterialIndex1Selected(materialRow) {
      // console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
      let {materialId, materialName, materialCode, materialType, costPrice} = materialRow
      this.form.setFieldsValue({output: materialId})
      this.formModel = Object.assign({}, this.formModel, {output: materialId, outputObject: materialRow})
    }
  }
}
</script>
